package cn.edu.ctbu.datajpa01.api;


import cn.edu.ctbu.datajpa01.domain.Student;
import cn.edu.ctbu.datajpa01.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


//只返回数据  返回给前端
@RestController
@RequestMapping("/api")
@Slf4j//使用log.info
public class StudentApiController {

    @Autowired
    private StudentService studentservice;

    @GetMapping("/student/list")
    public List<Student> list(HttpServletRequest httpServletRequest) throws Exception {
        if (!judageLogin(httpServletRequest)) {
            throw new Exception("未登录！");
        }
        HttpSession session = httpServletRequest.getSession();
        String username = (String) session.getAttribute("user_name");
        if (username == null || username.equals("")) {
            //无权读取
            return null;
        }
        return studentservice.findAll();
    }


    //响应
    @RequestMapping("/student/list")//子路径
    public List<Student> list() {
        return studentservice.findAll();//返回学生列表数据
    }

    @PostMapping("student/insert")
    public void insert(Student student) {


        studentservice.insert(student);
        log.info(student.toString());
    }

    private Boolean judageLogin(HttpServletRequest httpServletRequest) {
        HttpSession session = httpServletRequest.getSession();
        String username = (String) session.getAttribute("user_name");
        if (username == null || username.equals("")) {
            //无权读取
            return false;
        }
        return true;
    }
}

